package org.zhiyootech.resources;

import org.apache.commons.beanutils.BeanUtils;
import org.eclipse.microprofile.jwt.JsonWebToken;
import org.jboss.logging.Logger;
import org.zhiyootech.base.annotation.Login;
import org.zhiyootech.base.domain.R;
import org.zhiyootech.domain.UserInfoRequest;
import org.zhiyootech.entity.UserInfo;
import org.zhiyootech.service.UserInfoService;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;

@Path("/user")
@RequestScoped
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class WeChartUserInfoResource {

    private static final Logger logger = Logger.getLogger(WeChartUserInfoResource.class);

    @Inject
    JsonWebToken jwt;
    @Inject
    UserInfoService userInfoService;

    @GET
    @Path("getUserInfo")
    @PermitAll
    @Login
    public String getUserInfo(@Context SecurityContext ctx) {
        Principal caller = ctx.getUserPrincipal();
        String name = caller == null ? "anonymous" : caller.getName();
        boolean hasJWT = jwt.getClaimNames() != null;
        String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s, hasJWT: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme(), hasJWT);
        UserInfo userInfo = userInfoService.findByOpenId("");
        if (null == userInfo) {
            return helloReply;
        }
        return userInfo.getCstName();
    }

    /**
     * 补充客户信息
     *
     * @return Response
     */
    @POST
    @Path("/extraCustomerInfo")
    @PermitAll
    @Login
    public R extraCustomerInfo(@Valid UserInfoRequest userInfoRequest) {
        UserInfo userInfo = new UserInfo();
        try {
            BeanUtils.copyProperties(userInfo, userInfoRequest);
            userInfoService.save(userInfo);
            return R.builder()
                    .build()
                    .ok();
        } catch (Exception e) {
            logger.error("补充客户信息失败", e);
            return R.builder()
                    .message("补充客户信息失败")
                    .build()
                    .fail();
        }
    }

    /**
     * 新增客户信息
     *
     * @return
     */
    @POST
    @Path("saveNewCst")
    @RolesAllowed("Merchant")
    public Response saveNewCst(UserInfo entity) {
        boolean save = userInfoService.save(entity);
        if (save) {
            return Response.ok().build();
        }
        return Response.serverError().build();
    }
}
